package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import app.cloudstringers.Home;
import define.API;
import define.Constants;
import define.Key;

public class UpdateTaskManagerAsync extends AsyncTask<String, Void, Boolean> {

	private Context context;
	
	public UpdateTaskManagerAsync(Context context) {
		this.context = context;
	}
	
	@Override
	protected Boolean doInBackground(String... params) {
		/**
		 * Call Status API to show the files in List View
		 */
		HttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mHttpPost = new HttpPost(API.TASK_UPDATE_STATE);
		List<NameValuePair> mNameValues = new ArrayList<NameValuePair>(3);

		mNameValues.add(new BasicNameValuePair(Key.KEY_USER_ID, params[0]));
		mNameValues.add(new BasicNameValuePair(Key.KEY_TASK_ID, params[1]));
		mNameValues.add(new BasicNameValuePair(Key.KEY_TASK_STATE, params[2]));

//		Log.i("", "user_id " + params[0]);
//		Log.i("", "task_id " + params[1]);
//		Log.i("", "task_state " + params[2]);
		
		try {
			mHttpPost.setEntity(new UrlEncodedFormEntity(mNameValues));
			HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);
			
//			Log.i("", "" + XML);
			
			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		
		Constants.utils.showProgressDialog();
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		
		/**
		 * Refresh Task Manager page to get new List
		 */
		if (result) {
			new GetTaskManagerAsync(context).execute(Home.ID);
		}
		
		Constants.utils.hideProgressDialog();
	}
}
